

const db = require("../db/index")

//获取属性（参数）
const getCateAttribute = (req, res) => {
    console.log(req.query);
    let sql = "select * from sp_attribute where cat_id = ? and is_del=0" //and attr_sel= ?
    db.query(sql, req.query.cat_id, (err, result) => {
        if (err) return res.sendErr(err)
        //查询不到就是没参数 不报错
        // if (result.length === 0) return res.sendErr(err)

        let onlyArr = []
        let manyArr = []
        //分出result：only/many
        result.forEach(item => {
            if (item.attr_sel === "only") {
                onlyArr.push(item)
            } else {
                manyArr.push(item)
            }
        });

        res.send({
            status: 200,
            message: "获取分类参数成功!",
            data: {
                onlyArr,
                manyArr
            },
        })
    })
}

//删除属性（参数）
const delCateAttribute = (req, res) => {
    console.log(req.query);
    let sql = "update sp_attribute set is_del=1 where attr_id=?"
    db.query(sql, req.query.attr_id, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("删除该参数失败!")
        res.send({
            status: 200,
            message: "删除改参数成功!"
        })
    })
}

// 属性更改
const editCateAttribute = (req, res) => {
    // ==============================================
    let sql = "update sp_attribute set ? where attr_id = ?"
    db.query(sql, [req.body, req.body.attr_id], (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("参数属性更改失败!")

        res.send({
            status: 200,
            message: "参数属性更改成功!"
        })
    })
}

//添加属性（参数）
const addCateAttribute = (req, res) => {
    // cat_id attr_name attr_sel attr_vals
    // console.log(req.body);
    req.body.attr_write = req.body.attr_sel === "only" ? "manual" : "list"

    let sql = "insert into sp_attribute set ?"
    db.query(sql, req.body, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("添加该参数失败!")

        res.send({
            status: 200,
            message: "添加参数成功!"
        })
    })
}

module.exports = {
    getCateAttribute,
    delCateAttribute,
    editCateAttribute,
    addCateAttribute
}